#include "RoDebugViewerComponent.h"
#include "RoStanzas.h"
#include "RoXmlStream.h"
#include "RoQuery.h"

RoDebugViewerComponent::RoDebugViewerComponent(RoModule *parent) :
    super(parent)
{
    setName("RoDebugViewerComponent");
}

void RoDebugViewerComponent::receive_query_result(bool error, QDomDocument answer)
{
    if(error)
    {
        qDebug() << "error occured";
    }

    QDomElement docElement = answer.documentElement();
    if(docElement.tagName() == "components")
    {
        QMap<QString,QString> components;

        QDomNode n = docElement.firstChild();
        while( !n.isNull() )
        {
            QDomElement e = n.toElement();
            if( !e.isNull() &&
                (e.tagName() == "component") )
            {
                components.insert(e.attribute("name"), "");
            }
            n = n.nextSibling();
        }
        if(!components.isEmpty())
            emit receivedComponents(components);
    }
    else if(docElement.tagName() == "methods")
    {
        QList<Component::Function> methods;

        QDomNode n = docElement.firstChild();
        while( !n.isNull() )
        {
            QDomElement e = n.toElement();
            if( !e.isNull() &&
                (e.tagName() == "method") )
            {
                methods.push_back(
                        *(new Component::Function(e.attribute("name") ) )
                        );
            }
            if(e.hasChildNodes())
            {
                QDomNode methodContent = e.firstChild();
                while( !methodContent.isNull() )
                {
                    QDomElement ce = methodContent.toElement();

                    if( !ce.isNull() && ( ce.tagName() == "description" ) )
                    {
                        methods.last().setDescription( ce.text() );
                    }
                    else if( !ce.isNull() && ( ce.tagName() == "example" ) )
                    {
                        methods.last().setExample( ce.text() );
                    }
                    methodContent = methodContent.nextSibling();
                }
            }
            n = n.nextSibling();
        }
        if( !methods.isEmpty() )
        {
            RoQuery* query = qobject_cast<RoQuery*>(sender());
            emit receivedMethods(query->remoteComponentName(), methods);
        }
    }

    sender()->deleteLater();
}

void RoDebugViewerComponent::receive_stanza_info(RoInfoStanza stanza)
{
    emit receivedNewInfo(stanza);
}
